package com.xhwl.centiotdata.suppliersystem.eesd.kede;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.xhwl.centiotdata.pojo.constant.KeDeConstant;
import com.xhwl.centiotdata.utils.RedisUtils;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.device.DeviceProjSupplierCategory;
import com.xhwl.common.utils.ChkUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author tangwei
 * @description 科德水电子系统
 * @create 2023-05-04 10:37
 */
@Slf4j
@Component
public class KeDeUtil {

    @Autowired
    private RedisUtils redisUtils;

    // 科德子系统默认Token有效期是120分钟有效
    private static final int DEFAULT_MINUTE = 120;
    // 成功返回状态码
    private static final Integer SUCCESS_CODE = 200;
    // 失败返回状态码
    private static final Integer FAIL_CODE = 500;

    /**
     * POST请求
     */
    public ResultJson postWithAuth(DeviceProjSupplierCategory config, Map<String, Object> params, String api) {
        JSONObject properties = config.getProperties();
        String result;
        try {
            Map<String, String> header = new HashMap<>();
            header.put("X-HW-ID", properties.getString("appId"));
            header.put("X-HW-APPKEY", properties.getString("appKey"));
            result = HttpUtil.createPost(api)
                    .addHeaders(header)
                    .form(params)
                    .setConnectionTimeout(10000)
                    .setReadTimeout(10000)
                    .execute()
                    .body();
        } catch (HttpException e) {
            log.error("【KEDE post】path:{};params:{}; request failed;错误信息=>{}", api, JSON.toJSONString(params), e.getMessage());
            throw new BusinessException(e.getMessage());
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        // log.error("科德_POST==>{}", jsonObject);
        return handleResultJson(jsonObject, api, result);
    }

    /**
     * GET请求
     */
    public ResultJson getWithAuth(DeviceProjSupplierCategory config, Map<String, Object> params, String api) {
        JSONObject properties = config.getProperties();
        String result;
        try {
            Map<String, String> header = new HashMap<>();
            header.put("X-HW-ID", properties.getString("appId"));
            header.put("X-HW-APPKEY", properties.getString("appKey"));
            result = HttpUtil.createGet(api)
                    .addHeaders(header)
                    .form(params)
                    .setConnectionTimeout(10000)
                    .setReadTimeout(10000)
                    .execute()
                    .body();
        } catch (HttpException e) {
            log.error("【KEDE post】path:{};params:{}; request failed;错误信息=>{}", api, JSON.toJSONString(params), e.getMessage());
            throw new BusinessException(e.getMessage());
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        return handleResultJson(jsonObject, api, result);
    }

    private ResultJson handleResultJson(JSONObject jsonObject, String api, String result) {
        // 科德成功返回
        if (Objects.equals(jsonObject.getInteger("code"), SUCCESS_CODE)) {
            return ResultJson.success(jsonObject);
        }
        // 酆泽成功返回
        if (jsonObject.containsKey("message") && Objects.equals(jsonObject.getString("message"), "success")) {
            return ResultJson.success(jsonObject);
        }
        log.error("科德系统调用==>{}接口,返回==>{}", api, result);
        // 针对有错误信息的返回
        if (Objects.equals(jsonObject.getInteger("code"), FAIL_CODE) && jsonObject.containsKey("msg")) {
            return ResultJson.fail(jsonObject.getString("msg"));
        }
        // 默认返回
        return ResultJson.fail("调用接口异常");
    }

    /**
     * 获取token,对接ROMA，无需鉴权
     */
    public String getToken(DeviceProjSupplierCategory config) {

        JSONObject properties = config.getProperties();
        String host = properties.getString("ipAndPort");
        String appKey = properties.getString("ak");
        String appSecret = properties.getString("sk");
        String api = host + KeDeConstant.GET_TOKEN;

        Object ret = redisUtils.get("KEDE.TOKEN");
        if (ret != null) {
            return (String) ret;
        }
        // 封装参数
        Map<String, Object> map = Maps.newHashMap();
        map.put("appId", appKey);
        map.put("appSecret", appSecret);
        map.put("grantType", "authorization_code");
        // 鉴权
        String result = HttpUtil.get(api, map, 3000);
        log.info("==========>科德水电子系统鉴权结果{}<============", result);
        if (StringUtils.isBlank(result)) {
            throw new RuntimeException("科德水电系统Token认证失败");
        }

        Map<String, Object> res = JSON.parseObject(result, Map.class);
        if (Objects.isNull(res)) {
            throw new RuntimeException(result);
        }
        if (ChkUtil.getInteger(res.get("code")) != SUCCESS_CODE) {
            throw new RuntimeException(result);
        }
        String accessToken = res.get("token").toString();
        redisUtils.setWithMinute("KEDE.TOKEN", accessToken, DEFAULT_MINUTE);
        return "Bearer " + accessToken;
    }
}
